<template>
  <div class="login-container">
    <!-- 去掉 el-card 组件，因为它可能带有边框 -->
    <div class="login-content">
      <h3>登录页面</h3>
      <el-form :model="loginForm" :rules="loginRules" ref="formRef" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="loginForm.username" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="loginForm.password" type="password" placeholder="请输入密码"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleLogin">登录</el-button>
          <el-button @click="handleGoToEnroll">注册</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import axios from 'axios';

// 引入路由实例
const router = useRouter();

// 定义表单数据
const loginForm = ref({
  username: '',
  password: ''
});

// 定义表单验证规则
const loginRules = ref({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ]
});

// 定义表单引用
const formRef = ref(null);
formRef.value = undefined;

// 处理登录逻辑
const handleLogin = async () => {
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const response = await axios.post('http://localhost:8081/api/users//login', loginForm.value);
        const { success, message } = response.data;
        if (success) {
          alert('登陆成功')
          await router.push('/');
        } else {
          alert(message);
        }
      } catch (error) {
        console.error('登录请求出错:', error);
        alert('登录请求出错，请稍后重试');
      }
    } else {
      console.log('表单验证失败');
    }
  });
};

// 处理跳转到注册页面逻辑
const handleGoToEnroll = () => {
  router.push('/enroll');
};
</script>

<style scoped>
.login-container {
  background-color: #e0f7fa; /* 浅蓝色背景 */
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}

.login-content {
  width: 350px;
  /* 可以根据需要添加其他样式，如背景色等 */
  background-color: #fff;
  padding: 20px;
}
</style>